package oocl.ita.eordering.controller;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.JsonProcessingException;

import oocl.ita.eordering.po.Client;
import oocl.ita.eordering.po.Food;
import oocl.ita.eordering.po.Merchant;
import oocl.ita.eordering.po.Order;
import oocl.ita.eordering.service.FoodService;
import oocl.ita.eordering.service.MerchantService;
import oocl.ita.eordering.service.OrderService;
import oocl.ita.eordering.util.JSONUtil;
import oocl.ita.eordering.vo.Vfood;
import oocl.ita.eordering.webService.GetFoodRecommendWS;
import oocl.ita.eordering.webService.GetMerchantPassWS;

@Controller
@RequestMapping("/action")
public class CartLogicController {

	@Autowired(required = true)
	private OrderService orderService;
	@Autowired
	GetMerchantPassWS getMerchantPassWS;
	@Autowired(required = true)
	private FoodService foodService;
	@Autowired
	GetFoodRecommendWS getFoodRecommendWS;

	// 购物车存session缓存
	@SuppressWarnings("unchecked")
	@RequestMapping("/addToCart")
	@ResponseBody
	public Vfood addtoCart(int fId, int type, Integer num, HttpSession session) {
		Map<Integer, Vfood> foods;
		foods = (Map<Integer, Vfood>) session.getAttribute("foodCart");
		if (foods == null) {
			foods = new HashMap<>();
		}
		List<Food> fList = (List<Food>) session.getAttribute("foods");
		Vfood vfood = null;
		vfood = foods.get(fId);
		if (type == 1) {
			if (vfood != null) {
				vfood.setNum(vfood.getNum() + 1);
			} else {
				for (Food food : fList) {
					if (fId == food.getfId()) {
						vfood = new Vfood(food);
						break;
					}
				}
				foods.put(fId, vfood);
			}
		} else {
			vfood.setNum(num);
			if (num == 0)
				foods.remove(fId);
		}
		session.setAttribute("foodCart", foods);
		System.out.println("foodCart.size:" + foods.size());
		return vfood;
	}

	// 异步展示session中用户的购物车
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping("/showUserCart")
	@ResponseBody
	public List<Vfood> showUserCart(int mId, HttpSession session) {
		Map<Integer, Vfood> foods;
		foods = (Map<Integer, Vfood>) session.getAttribute("foodCart");
		if (foods == null) {
			return null;
		}
		List<Vfood> foodlist = new ArrayList<>();
		Iterator<?> iter = foods.entrySet().iterator();
		while (iter.hasNext()) {
			Map.Entry entry = (Map.Entry) iter.next();
			Vfood val = (Vfood) entry.getValue();
			if (val.getmId() == mId)
				foodlist.add(val);
		}
		return foodlist;

	}

	// 添加订单
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping("/addOrder")
	@ResponseBody
	public Order addOrder(int mId, HttpSession session) {
		// webservice to find status for Merchant from A
		List<Merchant> merchants = getMerchantPassWS.getMechantPass();
		for (Merchant merchant : merchants) {
			if (merchant.getmId() == mId) {
				System.out.println("order: mid:" + mId);
				Map<Integer, Vfood> foods;
				foods = (Map<Integer, Vfood>) session.getAttribute("foodCart");
				if (foods == null) {
					return null;
				}
				List<Vfood> foodlist = new ArrayList<>();
				Iterator<?> iter = foods.entrySet().iterator();
				while (iter.hasNext()) {
					Map.Entry entry = (Map.Entry) iter.next();
					Vfood val = (Vfood) entry.getValue();
					if (val.getmId() == mId) {
						foodlist.add(val);
						iter.remove();
					}
				}
				String string = "";
				try {
					string = JSONUtil.objetc2Json(foodlist);
					System.out.println(string);
				} catch (JsonProcessingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				Client client = (Client) session.getAttribute("c");
				Order order = new Order(client.getcId(), mId, string, 1, new Date(), null, null, null);
				orderService.addOrder(order);
				return order;
			}

		}
		dataInit(session);
		return null;

	}

	@RequestMapping("/getUserLocation")
	@ResponseBody
	public Client getUserLocation(HttpSession session) {
		Client client = (Client) session.getAttribute("c");

		return client;
	}

	private void dataInit(HttpSession session) {
		List<Merchant> merchants = getMerchantPassWS.getMechantPass();
		session.getServletContext().setAttribute("merchants", merchants);
		for (Merchant merchant : merchants) {
			System.out.println(merchant.getmTel());
		}

		List<String> fidList = getFoodRecommendWS.getMechantPass();
		List<Vfood> fList = new ArrayList<Vfood>();
		for (String s : fidList) {
			Integer i = Integer.parseInt(s);
			System.out.println(foodService.findFoodById(i).getfName());
			Vfood v = new Vfood(foodService.findFoodById(i));
			fList.add(v);
		}
		session.getServletContext().setAttribute("fList", fList);
		System.out.println("recommend foods:....." + fList.size());

		System.out.println("Init.....Success!");
	}

}
